package yt.spider.activity;

import android.content.Intent;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.monke.mprogressbar.MHorProgressBar;
import com.monke.mprogressbar.OnProgressListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.grantland.widget.AutofitTextView;
import yt.spider.R;
import yt.spider.SimpleObserver;
import yt.spider.bean.BookContentBean;
import yt.spider.bean.BookContentBeanDao;
import yt.spider.bean.BookInfoBeanDao;
import yt.spider.bean.BookShelfBean;
import yt.spider.bean.ReadBookContentBean;
import yt.spider.bean.ReplaceRuleBean;
import yt.spider.dao.DbHelper;
import yt.spider.events.MessageEvent;
import yt.spider.help.BookshelfHelp;
import yt.spider.manage.BitIntentDataManager;
import yt.spider.manage.ReplaceRuleManage;
import yt.spider.view.BookContentView;
import yt.spider.view.ChapterListView;
import yt.spider.view.ContentSwitchView;

/**
 * Created by songyuanjin on 2018/4/8.
 */

public class ReadBookActivity extends BaseActivity {
    private final int ResultReplace = 101;
    private final int RESULT_OPEN_OTHER_PERMS = 102;
    public final int ResultSelectBg = 103;
    public final static int OPEN_FROM_OTHER = 0;
    public final static int OPEN_FROM_APP = 1;

    private Boolean isAdd = false; //判断是否已经添加进书架
    private int open_from;
    private BookShelfBean bookShelf;

    private int pageLineCount = 5;   //假设5行一页
    private int pageWidth;

    private int numberOfRetries = 0;

    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.csv_book)
    ContentSwitchView csvBook;
    @BindView(R.id.fl_menu)
    FrameLayout flMenu;
    @BindView(R.id.v_menu_bg)
    View vMenuBg;
    @BindView(R.id.ll_menu_top)
    LinearLayout llMenuTop;
    @BindView(R.id.ll_menu_bottom)
    LinearLayout llMenuBottom;
    @BindView(R.id.iv_return)
    ImageButton ivReturn;
    @BindView(R.id.iv_refresh)
    ImageButton ivRefresh;
    @BindView(R.id.iv_more)
    ImageView ivMenuMore;
    @BindView(R.id.atv_title)
    AutofitTextView atvTitle;
    @BindView(R.id.atv_url)
    AutofitTextView atvUrl;
    @BindView(R.id.tv_pre)
    TextView tvPre;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.hpb_read_progress)
    MHorProgressBar hpbReadProgress;
    @BindView(R.id.ll_catalog)
    LinearLayout llCatalog;
    @BindView(R.id.ll_light)
    LinearLayout llLight;
    @BindView(R.id.ll_font)
    LinearLayout llFont;
    @BindView(R.id.ll_setting)
    LinearLayout llSetting;
    @BindView(R.id.clp_chapterlist)
    ChapterListView chapterListView;

    private boolean aloudButton;
    private boolean hideStatusBar;
    private boolean isBind;
    private String noteUrl;

    //主菜单动画
    private Animation menuTopIn;
    private Animation menuTopOut;
    private Animation menuBottomIn;
    private Animation menuBottomOut;

    private ContentSwitchView.LoadDataListener loadDataListener;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            noteUrl = savedInstanceState.getString("noteUrl");
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_read);
        ButterKnife.bind(this);

        initCsvBook();
        setEvents();
        initData();
        initLoadDataListener();
        //正文
        csvBook.setLoadDataListener(loadDataListener);

        initAnimation();
        initChapterList();
    }

    private void initAnimation() {
        menuTopIn = AnimationUtils.loadAnimation(this, R.anim.anim_readbook_top_in);
        menuBottomIn = AnimationUtils.loadAnimation(this, R.anim.anim_readbook_bottom_in);
        //隐藏菜单
        menuTopOut = AnimationUtils.loadAnimation(this, R.anim.anim_readbook_top_out);
        menuBottomOut = AnimationUtils.loadAnimation(this, R.anim.anim_readbook_bottom_out);
        menuTopIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                hideStatusBar(false);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                vMenuBg.setOnClickListener(v -> popMenuOut());
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        menuTopOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                vMenuBg.setOnClickListener(null);
                hideStatusBar(hideStatusBar);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                flMenu.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    @OnClick(R.id.v_menu_bg)
    void onClickMenu() {
        llMenuBottom.setVisibility(View.VISIBLE);
    }


    /**
     * 隐藏虚拟按键
     */
    private void hideNavigationBar() {
       /* if (preferences.getBoolean("hide_navigation_bar", false)) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav
                            | View.SYSTEM_UI_FLAG_IMMERSIVE);
        }*/
    }

    /**
     * 显示菜单
     */
    private void popMenuIn() {
        flMenu.setVisibility(View.VISIBLE);
        llMenuTop.startAnimation(menuTopIn);
        llMenuBottom.startAnimation(menuBottomIn);
        hideStatusBar(false);
        hideNavigationBar();
    }

    /**
     * 隐藏菜单
     */
    private void popMenuOut() {
        if (flMenu.getVisibility() == View.VISIBLE) {
            llMenuTop.startAnimation(menuTopOut);
            llMenuBottom.startAnimation(menuBottomOut);
        }
    }

    public void initData() {
        Log.d("SYJ_", "initData()");
        Intent intent = getIntent();
        open_from = intent.getIntExtra("from", OPEN_FROM_APP);
        if (open_from == OPEN_FROM_APP) {
            String noteUrl = this.noteUrl;
            Log.d("SYJ_", "initData() OPEN_FROM_APP noteUrl is :" + noteUrl);
            if (noteUrl != null && !noteUrl.isEmpty()) {
                bookShelf = BookshelfHelp.getBook(noteUrl);
            }
            if (bookShelf == null) {
                String key = intent.getStringExtra("data_key");
                bookShelf = (BookShelfBean) BitIntentDataManager.getInstance().getData(key);
                BitIntentDataManager.getInstance().cleanData(key);
            }
            if (bookShelf == null) {
                //mView.finish();
                return;
            }
            if (!bookShelf.getTag().equals(BookShelfBean.LOCAL_TAG)) {
                //mView.showOnLineView();
                ivMenuMore.setVisibility(View.VISIBLE);
                ivRefresh.setVisibility(View.VISIBLE);
                atvUrl.setVisibility(View.VISIBLE);
            }
            csvBook.startLoading();
            checkInShelf();
        } else {
            //mView.openBookFromOther();
        }


    }

    /**
     * 隐藏状态栏
     */
    private void hideStatusBar(Boolean hide) {
        if (hide) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    private void checkInShelf() {
        Observable.create((ObservableOnSubscribe<Boolean>) e -> {
            List<BookShelfBean> temp = DbHelper.getInstance().getmDaoSession().getBookShelfBeanDao().queryBuilder().where(BookInfoBeanDao.Properties.NoteUrl.eq(bookShelf.getNoteUrl())).build().list();
            isAdd = !(temp == null || temp.size() == 0);
            e.onNext(isAdd);
            e.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SimpleObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean value) {
                        csvBook.startLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }
                });
    }

    private void setEvents() {

        //上一章
        tvPre.setOnClickListener(view -> {
            if (bookShelf != null) {
                csvBook.setInitData(bookShelf.getDurChapter() - 1,
                        bookShelf.getChapterListSize(),
                        BookContentView.DurPageIndexBegin);
            }
        });

        //下一章
        tvNext.setOnClickListener(view -> {
            if (bookShelf != null) {
                csvBook.setInitData(bookShelf.getDurChapter() + 1,
                        bookShelf.getChapterListSize(),
                        BookContentView.DurPageIndexBegin);
            }
        });

        //下面的菜单展开目录
        llCatalog.setOnClickListener(view -> {
            ReadBookActivity.this.popMenuOut();
            if (chapterListView.hasData()) {
                new Handler().postDelayed(() -> chapterListView.show(bookShelf.getDurChapter()), menuTopOut.getDuration());
            }
        });

        //目录 点击选中
        chapterListView.setOnChangeListener(new ChapterListView.OnChangeListener() {
            @Override
            public void animIn() {
                hideStatusBar(false);
            }

            @Override
            public void animOut() {
                hideStatusBar(hideStatusBar);
            }
        });
        //阅读进度
        hpbReadProgress.setProgressListener(new OnProgressListener() {
            @Override
            public void moveStartProgress(float dur) {

            }

            @Override
            public void durProgressChange(float dur) {

            }

            @Override
            public void moveStopProgress(float dur) {
                int realDur = (int) Math.ceil(dur);
                if ((realDur) != csvBook.getDurContentView().getDurPageIndex()) {
                    csvBook.setInitData(bookShelf.getDurChapter(),
                            bookShelf.getChapterListSize(),
                            realDur);
                }
                if (hpbReadProgress.getDurProgress() != realDur)
                    hpbReadProgress.setDurProgress(realDur);
            }

            @Override
            public void setDurProgress(float dur) {

            }
        });
        //返回按钮
        ivReturn.getDrawable().mutate();
        ivReturn.getDrawable().setColorFilter(getResources().getColor(R.color.tv_text_default), PorterDuff.Mode.SRC_ATOP);
        ivReturn.setOnClickListener(view -> finish());
    }

    /**
     * 正文事件
     */
    private void initLoadDataListener() {
        loadDataListener = new ContentSwitchView.LoadDataListener() {
            @Override
            public void loadData(BookContentView bookContentView, long qtag, int chapterIndex, int pageIndex) {
                //mPresenter.loadContent(bookContentView, qtag, chapterIndex, pageIndex);
                loadContent(bookContentView, qtag, chapterIndex, pageIndex);
            }

            @Override
            public void updateProgress(int chapterIndex, int pageIndex) {
                updateBookProgress(chapterIndex, pageIndex);
                bookShelf.setDurChapter(chapterIndex);
                bookShelf.setDurChapterPage(pageIndex);
                if (bookShelf.getChapterListSize() > 0) {
                    atvTitle.setText(bookShelf.getChapterList(chapterIndex).getDurChapterName());
                    atvUrl.setText(bookShelf.getChapterList(chapterIndex).getDurChapterUrl());
                } else {
                    atvTitle.setText("无章节");
                }
                if (bookShelf.getChapterListSize() == 1) {
                    tvPre.setEnabled(false);
                    tvNext.setEnabled(false);
                } else {
                    if (chapterIndex == 1) {
                        tvPre.setEnabled(false);
                        tvNext.setEnabled(true);
                    } else if (chapterIndex == bookShelf.getChapterListSize() - 1) {
                        tvPre.setEnabled(true);
                        tvNext.setEnabled(false);
                    } else {
                        tvPre.setEnabled(true);
                        tvNext.setEnabled(true);
                    }
                }
            }

            @Override
            public String getChapterTitle(int chapterIndex) {
                if (bookShelf.getChapterListSize() == 0) {
                    return "无章节";
                } else
                    return bookShelf.getChapterList(chapterIndex).getDurChapterName();
            }

            @Override
            public void initData(int lineCount) {
                pageLineCount = lineCount;
                pageWidth = csvBook.getContentWidth();
                initContent();
            }

            @Override
            public void showMenu() {
                popMenuIn();
            }

            @Override
            public void setHpbReadProgress(int pageIndex, int pageAll) {
                hpbReadProgress.setMaxProgress(pageAll - 1);
                if (hpbReadProgress.getDurProgress() != pageIndex)
                    hpbReadProgress.setDurProgress(pageIndex);
            }

            @Override
            public void readAloud(String content) {
            }

        };
    }

    public void initContent() {
        csvBook.setInitData(bookShelf.getDurChapter(), bookShelf.getChapterListSize(), bookShelf.getDurChapterPage());
    }

    public void loadContent(final BookContentView bookContentView, final long bookTag, final int chapterIndex, int pageIndex) {
        //载入正文
        if (null != bookShelf && bookShelf.getChapterListSize() > 0) {
            if (null != bookShelf.getChapterList(chapterIndex).getBookContentBean()
                    && null != bookShelf.getChapterList(chapterIndex).getBookContentBean().getDurChapterContent()) {
                if (bookShelf.getChapterList(chapterIndex).getBookContentBean().getLineSize() == csvBook.getTextPaint().getTextSize()
                        && bookShelf.getChapterList(chapterIndex).getBookContentBean().getLineContent() != null
                        && bookShelf.getChapterList(chapterIndex).getBookContentBean().getLineContent().size() > 0) {
                    //已有数据
                    int tempCount = (int) Math.ceil(bookShelf.getChapterList(chapterIndex)
                            .getBookContentBean().getLineContent().size() * 1.0 / pageLineCount) - 1;

                    if (pageIndex == BookContentView.DurPageIndexBegin) {
                        pageIndex = 0;
                    } else if (pageIndex == BookContentView.DurPageIndexEnd) {
                        pageIndex = tempCount;
                    } else {
                        if (pageIndex >= tempCount) {
                            pageIndex = tempCount;
                        }
                    }
                    int start = pageIndex * pageLineCount;
                    int end = pageIndex == tempCount ? bookShelf.getChapterList(chapterIndex).getBookContentBean().getLineContent().size() : start + pageLineCount;
                    if (bookContentView != null && bookTag == bookContentView.getQTag()) {
                        bookContentView.updateData(bookTag,
                                bookShelf.getChapterList(chapterIndex).getDurChapterName(),
                                bookShelf.getChapterList(chapterIndex).getBookContentBean().getLineContent().subList(start, end),
                                chapterIndex,
                                bookShelf.getChapterListSize(),
                                pageIndex,
                                tempCount + 1);
                    }
                } else {
                    //有元数据  重新分行
                    bookShelf.getChapterList(chapterIndex).getBookContentBean()
                            .setLineSize(csvBook.getTextPaint().getTextSize());
                    final int finalPageIndex = pageIndex;
                    SeparateParagraphToLines(bookShelf.getChapterList(chapterIndex).getBookContentBean().getDurChapterContent(), chapterIndex)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribeOn(Schedulers.io())
                            .subscribe(new SimpleObserver<List<String>>() {
                                @Override
                                public void onNext(List<String> value) {
                                    bookShelf.getChapterList(chapterIndex).getBookContentBean().setLineContent(value);
                                    loadContent(bookContentView, bookTag, chapterIndex, finalPageIndex);
                                }

                                @Override
                                public void onError(Throwable e) {
                                    if (bookContentView != null && bookTag == bookContentView.getQTag())
                                        bookContentView.loadError();
                                }
                            });
                }
            } else {
                final int finalPageIndex1 = pageIndex;
                Observable.create((ObservableOnSubscribe<ReadBookContentBean>) e -> {
                    List<BookContentBean> tempList = DbHelper.getInstance().getmDaoSession().getBookContentBeanDao().queryBuilder()
                            .where(BookContentBeanDao.Properties.DurChapterUrl.eq(bookShelf.getChapterList(chapterIndex).getDurChapterUrl())).build().list();
                    e.onNext(new ReadBookContentBean(tempList == null ? new ArrayList<>() : tempList, finalPageIndex1));
                    e.onComplete();
                }).observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(new SimpleObserver<ReadBookContentBean>() {
                            @Override
                            public void onNext(ReadBookContentBean tempList) {
                                if (tempList.getBookContentList() != null && tempList.getBookContentList().size() > 0
                                        && tempList.getBookContentList().get(0).getDurChapterContent() != null) {
                                    bookShelf.getChapterList(chapterIndex).setBookContentBean(tempList.getBookContentList().get(0));
                                    loadContent(bookContentView, bookTag, chapterIndex, tempList.getPageIndex());
                                    //加载下一章节
                                    //LoadNextChapter(chapterIndex);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                            }
                        });
            }
        } else {
            if (bookContentView != null && bookTag == bookContentView.getQTag())
                bookContentView.loadError();
        }
    }


    /**
     * @param paragraphStr 内容
     * @return 分行内容
     */
    private Observable<List<String>> SeparateParagraphToLines(String paragraphStr, int chapterIndex) {
        return Observable.create(e -> {
            String content = paragraphStr;
            if (!content.startsWith(bookShelf.getChapterList(chapterIndex).getDurChapterName())) {
                content = String.format("%s\r\n%s", bookShelf.getChapterList(chapterIndex).getDurChapterName(), paragraphStr);
            }
            String allLine[] = content.split("\r\n\u3000\u3000");
            //替换
            if (ReplaceRuleManage.getEnabled() != null && ReplaceRuleManage.getEnabled().size() > 0) {
                StringBuilder contentBuilder = new StringBuilder();
                for (String line : allLine) {
                    for (ReplaceRuleBean replaceRule : ReplaceRuleManage.getEnabled()) {
                        try {
                            line = line.replaceAll(replaceRule.getRegex(), replaceRule.getReplacement());
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (line.length() > 0) {
                        if (contentBuilder.length() == 0) {
                            contentBuilder.append(line);
                        } else {
                            contentBuilder.append("\r\n").append("\u3000\u3000").append(line);
                        }
                    }
                }
                content = contentBuilder.toString();
            }
            TextPaint mPaint = (TextPaint) csvBook.getTextPaint();
            mPaint.setSubpixelText(true);
            Layout tempLayout = new StaticLayout(content, mPaint, pageWidth, Layout.Alignment.ALIGN_NORMAL, 0, 0, false);
            List<String> linesData = new ArrayList<>();
            for (int i = 0; i < tempLayout.getLineCount(); i++) {
                linesData.add(content.substring(tempLayout.getLineStart(i), tempLayout.getLineEnd(i)));
            }
            e.onNext(linesData);
            e.onComplete();
        });
    }

    private void initCsvBook() {
        csvBook.bookReadInit(() -> initData());
    }

    public void initChapterList() {
        chapterListView.setData(bookShelf, index -> csvBook
                .setInitData(index, bookShelf.getChapterListSize(),
                        BookContentView.DurPageIndexBegin));
    }

    public void updateBookProgress(int chapterIndex, int pageIndex) {
        bookShelf.setDurChapter(chapterIndex);
        bookShelf.setDurChapterPage(pageIndex);
    }

    public void saveProgress() {
        if (bookShelf != null) {
            Observable.create((ObservableOnSubscribe<BookShelfBean>) e -> {
                bookShelf.setFinalDate(System.currentTimeMillis());
                BookshelfHelp.saveBookToShelf(bookShelf);
                e.onNext(bookShelf);
                e.onComplete();
            }).subscribeOn(Schedulers.newThread())
                    .subscribe(new SimpleObserver<BookShelfBean>() {
                        @Override
                        public void onNext(BookShelfBean value) {
                            Log.d("SYJ", "success value :" + value.toString());
                            EventBus.getDefault().post(new MessageEvent());
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            Log.d("SYJ", "onError  :" + e.getMessage());

                        }
                    });
        }
    }

    public String getChapterTitle(int chapterIndex) {
        if (bookShelf.getChapterListSize() == 0) {
            return getString(R.string.no_chapter);
        } else
            return bookShelf.getChapterList(chapterIndex).getDurChapterName();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (bookShelf != null) {
            outState.putString("noteUrl", bookShelf.getNoteUrl());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveProgress();
    }
}
